package com.paris10.model;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.codehaus.jackson.annotate.JsonTypeName;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


@JsonTypeName("FluxRSS")
public class FluxRSS extends AbstractSource{
	
	
	public FluxRSS(){}
	
	public FluxRSS(String titre, String chemin){
		this.titre=titre;
		this.chemin=chemin;
		this.date= Dates.date();
	}
	
	public AbstractSource createSource(String titre, String chemin){
		return new FluxRSS(titre, chemin);
	}
	
	/**
     * Parser le fichier XML du flux RSS
     */
    public List<Article> rechercherMotsCles(String[] mots) {
    	
    	List<Article> listeArticles = new ArrayList<Article>();
    	
    	try{
    		
	    	DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
	        URL url = new URL(this.chemin);
	        Document doc = builder.parse(url.openStream());
	        NodeList nodes = null;
	        Element element = null;
	        /**
	         * Elements du flux RSS
	         **/
	        nodes = doc.getElementsByTagName("item");
	        
	        for (int i = 0; i < nodes.getLength(); i++) {
	            element = (Element) nodes.item(i);
	            ArticleRSS article = new ArticleRSS();
	            article.traiterData(element, mots);
	            if(article.isInteressant()){
	            	listeArticles.add(article);
	            }
	        } 
	    } catch (SAXException ex) {
	        Logger.getLogger(FluxRSS.class.getName()).log(Level.SEVERE, null, ex);
	    } catch (IOException ex) {
	        Logger.getLogger(FluxRSS.class.getName()).log(Level.SEVERE, null, ex);
	    } catch (ParserConfigurationException ex) {
	        Logger.getLogger(FluxRSS.class.getName()).log(Level.SEVERE, null, ex);
	    }
	        
    	return listeArticles;
    }
   
}
